package cn.sharp.android.ncr;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.*;
import android.widget.Toast;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by tukela on 2016/3/22.
 */
public class CameraActivity extends Activity {
    private SurfaceView surfaceView;
    private Camera camera;
    private boolean isPreview = false;
    private Handler handler= new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    show((String) msg.obj);
                    break;
                case 1:
                    show("调用失败！");
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();//得到窗口
        requestWindowFeature(Window.FEATURE_NO_TITLE);//没有标题
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置全屏
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//设置高亮
        setContentView(R.layout.activity_camera);
        surfaceView = (SurfaceView) findViewById(R.id.surfaceview);

//        surfaceView.getHolder().setFixedSize(800, 800);
        //下面设置surfaceView不维护自己的缓冲区,而是等待屏幕的渲染引擎将内容推送到用户面前
        surfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        surfaceView.getHolder().addCallback(new SurfaceCallback());
    }

    private void  initCamera(){
        if (!isPreview){

        }
    }

    private class SurfaceCallback implements SurfaceHolder.Callback, Camera.AutoFocusCallback {
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            try {
                camera = Camera.open();//打开硬件摄像头，这里导包得时候一定要注意是android.hardware.Camera
                WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);//得到窗口管理器
                Display display = wm.getDefaultDisplay();//得到当前屏幕
                Camera.Parameters parameters = camera.getParameters();//得到摄像头的参数
                parameters.setPreviewSize(display.getWidth(), display.getHeight());//设置预览照片的大小
//                parameters.setPreviewSize(500,300);//设置预览照片的大小
                parameters.setPreviewFrameRate(3);//设置每秒3帧
                parameters.setPictureFormat(PixelFormat.JPEG);//设置照片的格式
                parameters.setJpegQuality(85);//设置照片的质量
                parameters.setPictureSize(display.getWidth(),display.getHeight() );//设置照片的大小，默认是和     屏幕一样大
                parameters.setPictureSize(300,500 );//设置照片的大小，默认是和     屏幕一样大
//                parameters.set("orientation", "portrait");
                parameters.setRotation(90);
                camera.setParameters(parameters);
                camera.setDisplayOrientation(90);

                camera.setPreviewDisplay(surfaceView.getHolder());//通过SurfaceView显示取景画面
                camera.startPreview();//开始预览
                camera.autoFocus(this);//自动对焦
                isPreview = true;//设置是否预览参数为真
//                handler.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        camera.takePicture(null, null, new TakePictureCallback());
//                    }
//                }, 2000);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            try {
                handler.sendEmptyMessage(23);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            if (camera != null) {
                if (isPreview) {//如果正在预览
                    camera.stopPreview();
                    camera.release();
                }
            }
        }

        @Override
        public void onAutoFocus(boolean success, Camera camera) {
            if (success){
                show("聚焦成功");
               camera.takePicture(null, null, new TakePictureCallback());
            }

        }
    }




    private final class TakePictureCallback implements Camera.PictureCallback {
        public void onPictureTaken(byte[] data, Camera camera) {
            try {
                Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                File file = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
                FileOutputStream outputStream = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                outputStream.close();
                camera.stopPreview();
                camera.startPreview();//处理完数据之后可以预览
                show(file.getAbsolutePath());
            } catch (Exception e) {

            }
        }
    }


    public void setGetJson(byte[] data) {
        HttpUtils http = new HttpUtils();
        RequestParams params = new RequestParams();
//        params.addHeader("name", "value");
//        params.addQueryStringParameter("name", "value");
//
//// 只包含字符串参数时默认使用BodyParamsEntity，
//// 类似于UrlEncodedFormEntity（"application/x-www-form-urlencoded"）。
        params.addBodyParameter("username", "test");
        params.addBodyParameter("password", "test");
        params.addBodyParameter("recotype", "IdCard");
        params.addBodyParameter("b64", "0");
        params.addBodyParameter("image", "0");
        params.addBodyParameter("encoding", "utf-8");
        final Message message=handler.obtainMessage();
        message.what=0;
        http.send(HttpRequest.HttpMethod.POST, "cloud.exocr.com/recognize", params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String string=responseInfo.result;
                message.what=1;
                message.obj=string;
                handler.sendMessage(message);
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });
    }

    public void show(String str){
        Toast.makeText(this,str,Toast.LENGTH_LONG).show();
    }
}
